<template>
  <div class="app-container" v-loading="loadings">
    <!-- 基础信息 -->
    <h5 class="titleInfo">基础信息</h5>
    <el-form ref="form"   :rules="rules" :model="form" label-width="260px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="医院名称" prop="name">
            <el-input v-if="!$route.query.disabled" v-model="form.name" :disabled="true" />
            <el-input v-if="$route.query.disabled" v-model="form.name" />
          </el-form-item>
        </el-col>
        <!-- 3.2.0 -->
        <el-col :span="8">
          <el-form-item label="治疗室数量" prop="treatmentRoomNumber">
            <el-input v-model.number="form.treatmentRoomNumber">
              <template slot="append">间</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="医院简介" prop="description">
            <el-input v-model="form.description" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="省市区" prop="provinceId">
            <el-cascader v-model="selectedOptions" :options="options" @change="pcaList" />
          </el-form-item>
        </el-col>
        <!-- 3.2.0 -->
        <el-col :span="8">
          <el-form-item label="手术室数量" prop="operatingRoomNumber">
            <el-input v-model.number="form.operatingRoomNumber">
              <template slot="append">间</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" />
            <el-button type="text" @click="getLngLat">获取经纬度</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否上架" prop="status">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option
                v-for="item in statusOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 3.2.0 -->
        <el-col :span="8">
          <el-form-item label="医院面积" prop="acreage">
            <el-input v-model.number="form.acreage">
              <template slot="append">平</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否置顶" prop="isTop">
            <el-select v-model="form.isTop" placeholder="请选择">
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属分公司" prop="officeId">
            <!-- <el-input v-model="form.officeId"></el-input> -->
            <el-select
              filterable
              v-if="officeOption.length"
              v-model="form.officeId"
              placeholder="请选择"
            >
              <el-option
                v-for="item in officeOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 3.2.0 -->
        <el-col :span="12">
          <el-form-item label="成立时间" prop="establishAt">
            <el-date-picker
              v-model="form.establishAt"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="经度" prop="lng">
            <el-input v-model="form.lng" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="纬度" prop="lat">
            <el-input v-model="form.lat" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="医院标签">
            <!-- <el-input v-model="form.tagsId"></el-input> -->
            <el-select v-if="tagOption.length" v-model="form.labelsId" placeholder="请选择">
              <el-option label="默认" :value="0" />
              <el-option label="90天不满意退款" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="医院类型" prop="tagsId">
            <el-select v-if="tagOption.length" v-model="form.tagsId" placeholder="请选择">
              <el-option
                v-for="item in tagOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="贷款平台">
            <el-select v-model="form.loanId" v-if="loanOption.length" placeholder="请选择">
              <el-option
                v-for="item in loanOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>-->
        <el-col :span="12">
          <el-form-item label="每日可预约次数" prop="appointmentNum">
            <el-input v-model="form.appointmentNum" @blur="numBlur" />
            <p v-if="form.appointmentNum=='0'" style="color:red;">0为不限次数</p>
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item label="是否支持90天不满意退款">
            <el-radio v-model="form.isNoReason" :label="0">否</el-radio>
            <el-radio v-model="form.isNoReason" :label="1">是</el-radio>
          </el-form-item>
        </el-col>-->
        <!-- 3.2.0 -->
         <el-col :span="12">
          <el-form-item label="全金币抵扣" prop="goldStatus">
            <el-radio v-model="form.goldStatus" :label="0">否</el-radio>
            <el-radio v-model="form.goldStatus" :label="1">是</el-radio>
          </el-form-item>
        </el-col>
     
        <el-col :span="12">
          <el-form-item label="诊疗范围">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="form.rangeTreatment"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- 图片信息 -->
      <div class="divBar" />
      <h5 class="titleInfo">图片信息</h5>
      <el-row>
        <el-col :span="24">
          <el-form-item label="LOGO" prop="logo">
            <!-- <newUpload
              ref="uploadImg1"
              :file-num="fileNum1"
              :file-list="fileList1"
              :width="imgWeith1"
              :height="imgHeight1"
            />-->
            <div class="newbox">
              <div class="newimg" v-for="(item, index) in fileList1" :key="index">
                <img :src="item.url" alt />
                <span @click="close(index,1)">X</span>
              </div>

              <imgload :width="imgWeith1" :height="imgHeight1" type="1" @imgfun="imgfun"></imgload>
            </div>

            <p>图片尺寸800px*800px</p>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="医院图片" prop="imageList">
            <!-- <newUpload
              ref="uploadImg2"
              :file-num="fileNum2"
              :file-list="fileList2"
              :width="imgWeith2"
              :height="imgHeight2"
            />-->
            <div class="newbox">
              <div class="newimg" v-for="(item, index) in fileList2" :key="index">
                <img :src="item.url" alt />
                <span @click="close(index,2)">X</span>
              </div>
              <imgload :width="imgWeith2" :height="imgHeight2" type="2" @imgfun="imgfun"></imgload>
            </div>
            <p>最多添加12张图片，图片尺寸800px*600px</p>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="90天无理由退款">
            <!-- <newUpload
              ref="uploadImg3"
              :file-num="fileNum3"
              :file-list="fileList3"
              :width="190"
              :height="190"
            />-->
            <div class="newbox">
              <div
                class="newimg"
                v-for="(item, index) in fileList3"
                v-if="fileList3.length"
                :key="index"
              >
                <img :src="item.url" alt />
                <span @click="close(index,3)">X</span>
              </div>
              <imgload :width="800" :height="600" type="3" @imgfun="imgfun"></imgload>
            </div>
            <p>最多添加3张图片，图片尺寸800px*600px</p>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="医院环境">
            <!-- <newUpload
              ref="uploadImg4"
              :file-num="fileNum4"
              :file-list="fileList4"
              :width="190"
              :height="190"
            />-->
            <div class="newbox">
              <div
                class="newimg"
                v-for="(item, index) in fileList4"
                v-if="fileList4.length"
                :key="index"
              >
                <img :src="item.url" alt />
                <span @click="close(index,4)">X</span>
              </div>
              <imgload :width="800" :height="600" type="4" @imgfun="imgfun"></imgload>
            </div>
            <p>最多添加3张图片，图片尺寸800px*600px</p>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="医院描述">
            <Tinymce v-if="flag" v-model="form.content" style="width:96%" />
          </el-form-item>
        </el-col>
      </el-row>
       <el-col :span="24">
      <el-form-item>
        <el-button
          v-if="this.$route.name!='hospitalInfo' "
          style="margin:30px 0"
          type="primary"
          @click="submitFn('form')"
        >立即提交</el-button>
      </el-form-item>
    </el-col>
    </el-form>
    
  </div>
</template>
<script>
import newUpload from "@/components/imgUpload/index";
import Tinymce from "@/components/Tinymce";
import imgload from "@/components/tailoring/index";
import { hospitalAdd, getGPS } from "@/api/hospitalAdd";
import { hospitalDetail, updateHospital } from "@/api/hospitalEdit";
import { companyList } from "@/api/branchOfficeDropDown";
import { loanDropDown } from "@/api/loanDropDown";
import { findHospitalTagsList } from "@/api/hospitalLabel";

export default {
  name: "HospitalEdit",
  components: { newUpload, Tinymce, imgload },
  data() {
    return {
      loadings: true,
      imgWeith1: 800,
      imgHeight1: 800,
      imgWeith2: 800,
      imgHeight2: 600,
      flag: true,
      fileNum1: 1,
      fileNum2: 12,
      fileNum3: 3,
      fileNum4: 3,
      fileList1: [],
      fileList2: [],
      fileList3: [],
      fileList4: [],
      officeOption: [],
      // hideUpload2:false,
      hideUpload3: false,
      hideUpload4: false,
      hideUpload5: false,
      userId: "",
      statusOption: [
        {
          value: 0,
          label: "是"
        },
        {
          value: 1,
          label: "否"
        }
      ],
      form: {
        name: "",
        tagsId: "",
        labelsId: 0,
        description: "",
        provinceId: "",
        cityId: "",
        address: "",
        lng: "",
        lat: "",
        status: "",
        isTop: "",
        loanId: "",
        officeId: "",
        appointmentNum: "",
        logo: "",
        star: "1",
        imageList: [],
        content: ""
      },
      tagOption: [],
      rules: {
        name: [{ required: true, message: "请输入医院名称", trigger: "blur" }],
        goldStatus: [
          { required: true, message: "请输入必填字段", trigger: "blur" }
        ],
        treatmentRoomNumber: [
          { required: true, message: "请输入治疗室数量", trigger: "blur" }
        ],
        operatingRoomNumber: [
          { required: true, message: "请输入手术室数量", trigger: "blur" }
        ],
        acreage: [
          { required: true, message: "请输入医院面积", trigger: "blur" }
        ],
        establishAt: [
          { required: true, message: "请输入成立时间", trigger: "blur" }
        ],
        description: [
          { required: true, message: "请输入医院简介", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择是否上架", trigger: "blur" }
        ],
        isTop: [{ required: true, message: "请选择是否上架", trigger: "blur" }],
        lng: [{ required: true, message: "请输入经度", trigger: "blur" }],
        lat: [{ required: true, message: "请输入纬度", trigger: "blur" }],
        officeId: [
          { required: true, message: "请选择所属分公司", trigger: "blur" }
        ],
        provinceId: [
          { required: true, message: "请输入省市区", trigger: "blur" }
        ],
        tagsId: [
          { required: true, message: "请选择医院标签", trigger: "blur" }
        ],
        labelsId: [
          { required: true, message: "请选择医院标签", trigger: "blur" }
        ],
        appointmentNum: [
          { required: true, message: "请输入每日预约次数", trigger: "blur" }
        ],
        logo: [{ required: true, message: "请上传医院logo", trigger: "blur" }],
        imageList: [
          { required: true, message: "请上传医院图片", trigger: "blur" }
        ],
        content: [
          { required: true, message: "请输入医院描述", trigger: "blur" }
        ]
      },
      options: [],
      loanOption: [],
      selectedOptions: [],
      list1: {},
      submitForm: {},
      stype: 0
    };
  },
  created() {
    if (this.$route.query.userId) {
      this.userId = this.$route.query.userId + "";
    }
    if (this.$route.query.hospitalname) {
      this.form.name = this.$route.query.hospitalname;
    }
    if (this.$route.query.type) {
      this.stype = this.$route.query.type;
    }
    // 省市区数据获取
    var addData = require("../../../../static/address/area.json");
    this.options = addData;
    // 分公司列表
    this.getCompanyList();
  },
  inject: ["reload"],
  mounted() {
    this.imgWeith2 = 750;
    this.imgHeight2 = 422;
    this.getInfo();
  },
  methods: {
    close(index, type) {
      if (type == 1) {
        this.fileList1.splice(index, 1);
      }
      if (type == 2) {
        this.fileList2.splice(index, 1);
      }
      if (type == 3) {
        this.fileList3.splice(index, 1);
      }
      if (type == 4) {
        this.fileList4.splice(index, 1);
      }
    },
    imgfun(res, type) {
      console.log(type);
      if (type == 1) {
        this.form.logo = res;
        if (this.fileNum1 == this.fileList1.length) {
          this.fileList1.splice(this.fileList1.length - 1, 1);
        }

        this.fileList1.push({
          url: localStorage.getItem("imgUrlPrefix") + res
        });
      }
      if (type == 2) {
        console.log(this.fileNum2);
        console.log(this.fileList2.length);
        if (this.fileNum2 == this.fileList2.length) {
          this.fileList2.splice(this.fileList2.length - 1, 1);
        }

        this.fileList2.push({
          url: localStorage.getItem("imgUrlPrefix") + res
        });
      }

      if (type == 3) {
        if (this.fileNum3 == this.fileList3.length) {
          this.fileList3.splice(this.fileList3.length - 1, 1);
        }

        this.fileList3.push({
          url: localStorage.getItem("imgUrlPrefix") + res
        });
      }

      if (type == 4) {
        if (this.fileNum4 == this.fileList4.length) {
          this.fileList4.splice(this.fileList4.length - 1, 1);
        }

        this.fileList4.push({
          url: localStorage.getItem("imgUrlPrefix") + res
        });
      }
    },

    // 获取经纬度
    getLngLat() {
      const datas = {
        id: this.form.address
      };
      getGPS(datas).then(res => {
        console.log(res);
        if (!res.data.code) {
          this.form.lng = res.data.data.lng;
          this.form.lat = res.data.data.lat;
        } else {
          this.$message({
            message: res.data.msg,
            type: "warning"
          });
        }
      });
    },
    // 可预约次数校验
    numBlur() {
      const reg = /^[+]{0,1}(\d+)$/;
      var re = new RegExp(reg);
      if (!re.test(this.form.appointmentNum)) {
        this.form.appointmentNum = null;
      }
    },
    getInfo() {
      if (this.userId) {
        const datas = { id: this.userId };
        // console.log(datas)
        hospitalDetail(datas).then(res => {
          if (res.data.code == 0) {
            res.data.data.loanId = res.data.data.loanId + "";
            res.data.data.acreage = res.data.data.acreage
              ?( res.data.data.acreage.toFixed(2)-0)
              : 0;
            console.log(res.data.data);
            this.form = res.data.data;
            this.form.province = "";
            this.form.city = "";
            this.form.district = "";
            this.selectedOptions = [
              res.data.data.provinceId,
              res.data.data.cityId,
              res.data.data.districtId
            ];
            this.fileList1 = [
              {
                url: localStorage.getItem("imgUrlPrefix") + res.data.data.logo
              }
            ];
            if (res.data.data.imageList) {
              res.data.data.imageList.forEach((e, index) => {
                // if(index==0){
                // this.hideUpload2 = true
                this.fileList2.push({
                  url:
                    localStorage.getItem("imgUrlPrefix") +
                    res.data.data.imageList[index]
                });
              });
            }

            if (res.data.data.supportRefundList) {
              res.data.data.supportRefundList.map(res => {
                const obj = {
                  url: localStorage.getItem("imgUrlPrefix") + res
                };
                this.fileList3.push(obj);
              });
              //    this.$refs.uploadImg3.getLength(this.fileList3);
            }
            if (res.data.data.environmentList) {
              res.data.data.environmentList.map(res => {
                const obj = {
                  url: localStorage.getItem("imgUrlPrefix") + res
                };
                this.fileList4.push(obj);
              });
              //  this.$refs.uploadImg4.getLength(this.fileList4);
            }
            // this.$refs.uploadImg1.getLength(this.fileList1)
            // this.$refs.uploadImg2.getLength(this.fileList2);
            // this.$refs.uploadImg3.getLength(this.fileList3);
            // this.$refs.uploadImg4.getLength(this.fileList4);
          } else {
            this.$message.warning(res.data.msg);
          }
          this.loadings = false;
        });
      } else {
        this.loadings = false;
      }
    },
    // 获取分公司列表
    getCompanyList() {
      companyList()
        .then(res => {
          const resData = res.data.data;
          const newData = [];
          resData.forEach(e => {
            newData.push({
              value: e.id,
              label: e.name
            });
          });
          this.officeOption = newData;
          this.officeOption = JSON.parse(JSON.stringify(this.officeOption));
        })
        .catch(error => {
          this.$message.error(error);
        });
      loanDropDown().then(res => {
        const resData = res.data.data;
        const newData = [];
        resData.forEach(e => {
          newData.push({
            value: e.id - 0,
            label: e.name
          });
        });
        this.loanOption = newData;
        // console.log(newData)
      });
      // 获取医院标签
      const datas = {
        pageNum: 1,
        pageSize: 999
      };
      findHospitalTagsList(datas).then(res => {
        const resData = res.data.data.list;
        const newData = [];
        resData.forEach(e => {
          newData.push({
            value: e.id,
            label: e.name
          });
        });
        this.tagOption = newData;
      });
    },
    // 省市区数据改变
    pcaList(value) {
      let e = this.selectedOptions;
      e = value;
      console.log(e);
      console.log(this.selectedOptions);
      this.form.provinceId = e[0];
      this.form.cityId = e[1];
      this.form.districtId = e[2];
    },
    // 字符串截取
    getCaption(obj) {
      var index = obj.lastIndexOf(".com");
      obj = obj.substring(index + 4, obj.length);
      // obj.match(/com(\S*)/)[1];
      return obj;
    },
    imgexent(src) {
      let url = localStorage.getItem("imgUrlPrefix");
      let obj;
      let arr = [];
      src.map(res => {
        if (res.url.indexOf("http") > -1) {
          obj = res.url.split(url)[1];
        }
        arr.push(obj);
      });

      console.log(arr);
      return arr;
    },
    // 修改提交
    submitFn(e) {
      if (this.form.appointmentNum - 0 > 999) {
        this.$message({
          showClose: true,
          message: "每日可预约次数不可超过999",
          type: "warning"
        });
        return;
      }
      console.log(this.fileList2);
      // this.form.logo = this.fileList1[0].url;
      this.form.imageList = this.imgexent(this.fileList2);
      this.form.supportRefundList = this.fileList3.length
        ? this.imgexent(this.fileList3)
        : [];
      this.form.environmentList = this.fileList4.length
        ? this.imgexent(this.fileList4)
        : [];
      //  this.form.imageList = this.$refs.uploadImg2.submitUpload();
      // this.form.supportRefundList = this.$refs.uploadImg3.submitUpload();
      // this.form.environmentList = this.$refs.uploadImg4.submitUpload();
      if (!this.$route.query.id) {
        this.form.hospitalInformationId = null;
      } else {
        this.form.hospitalInformationId = this.$route.query.id - 0;
      }

      this.$refs[e].validate(valid => {
        if (valid) {
          // const tf = this.form;
          // console.log(tf);
          // for (var n in tf) {
          //   if (tf[n] instanceof Array) {
          //     continue;
          //   }
          //   if (tf[n] !== (undefined || null)) {
          //     tf[n] += "";
          //   }
          // }

          const datas = { ...this.form };
          datas.tagsId = datas.tagsId.toString();
          datas.loanId = datas.loanId.toString();
          datas.officeId = String(datas.officeId);
          datas.appointmentNum = datas.appointmentNum - 0;

          datas.provinceId = datas.provinceId + "";
          datas.cityId = datas.cityId + "";
          datas.status = datas.status + "";

          console.log(JSON.stringify(datas));
          if (this.stype == 1) {
            datas.id = "";
            hospitalAdd(datas)
              .then(res => {
                console.log(res);
                if (res.data.code == 0) {
                  this.$message({
                    showClose: true,
                    message: "添加成功",
                    type: "success"
                  });
                  // this.$router.push("/hospitalIndex");
                  this.$router.go(-1);
                  this.reload();
                } else {
                  this.$message({
                    showClose: true,
                    message: res.data.msg,
                    type: "warning"
                  });
                }
              })
              .catch(error => {
                this.$message.error(error);
              });
          } else {
            updateHospital(datas)
              .then(res => {
                // console.log(res)
                if (res.data.code == 0) {
                  this.$message({
                    showClose: true,
                    message: "修改成功",
                    type: "success"
                  });
                  this.$router.push("/hospitalIndex");
                  this.reload();
                } else {
                  this.$message({
                    showClose: true,
                    message: res.data.msg,
                    type: "warning"
                  });
                }
              })
              .catch(error => {
                this.$message.error(error);
              });
          }
        } else {
          this.$message({
            message: "有必填项没填，不能提交咯",
            type: "warning"
          });
          return false;
        }
      });
    }
  }
};
</script>
<style scoped>
.newbox {
  position: relative;
  display: flex;
  align-items: center;
}
.newbox /deep/ .footerBtn {
  height: 34px;
  margin-left: 22px;
}
.newimg {
  width: 148px;
  height: 148px;
  margin-left: 25px;
  position: relative;
}
.newimg img {
  width: 100%;
  height: 100%;
}
.newimg span {
  position: absolute;
  font-size: 15px;
  right: 6px;
  top: 0;
  cursor: pointer;
}
.app-container {
  padding: 0px !important;
}
</style>
